/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 *
 * @author user
 */
public class KeyIO {

    public static void createKeyPair(int keysize, OutputStream pubKey, OutputStream priKey) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keysize);
        KeyPair keyPair = keyPairGenerator.genKeyPair();

        pubKey.write(keyPair.getPublic().getEncoded());
        priKey.write(keyPair.getPrivate().getEncoded());

        pubKey.close();
        priKey.close();
    }

    public static PrivateKey getPrivateKey(InputStream priKey) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException{
        byte[] keyBytes = new byte[priKey.available()];
        priKey.read(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey pk = kf.generatePrivate(ks);
        return pk;
    }

     public static PublicKey getPublicKey(InputStream pubKey) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException{
        byte[] keyBytes = new byte[pubKey.available()];
        pubKey.read(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec ks = new X509EncodedKeySpec(keyBytes);
        PublicKey pk = kf.generatePublic(ks);
        return pk;
    }

}
